package longrise.phone.com.bjjt_henan.widget.photo;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.android.FormParameter;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.util.Util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.widget.photo.bean.ImageFloder;

import static android.widget.GridView.STRETCH_COLUMN_WIDTH;

/**
 * Created by chengsan on 17/5/1.
 */

public class PhotoSelectView extends LFView implements Handler.Callback, ILFMsgListener {
    private Context context;
    private LinearLayout panelView;
    private ImageView backIV;
    private Button photosBtn;
    private GridView gridView;
    private PhotoAdapter photoAdapter;
    private PopupWindow popupWindow;

    /**
     * 存储文件夹中的图片数量
     */
    private int mPicsSize;
    /**
     * 图片数量最多的文件夹
     */
    private File mImgDir;
    /**
     * 所有的图片
     */
    private List<String> mImgs;

    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<String>();

    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();

    private Handler handler;

    private OnSelectImgFinishListener onSelectImgFinishListener;

    private int mode = 2;//照片选择模式 2:多张 1:单张
    private int maxSelectPhotoNum = 5;//一次最多可以选择多少张图片

    public PhotoSelectView(Context c) {
        super(c);
        this.context = c;
    }

    /**
     * 照片选择模式 2:多张 1:单张
     *
     * @param mode
     */
    public void setMode(int mode) {
        this.mode = mode;
    }

    /**
     * 一次最多可以选择多少张图片
     *
     * @param maxSelectPhotoNum
     */
    public void setMaxSelectPhotoNum(int maxSelectPhotoNum) {
        this.maxSelectPhotoNum = maxSelectPhotoNum;
    }

    public void setOnSelectImgFinishListener(OnSelectImgFinishListener onSelectImgFinishListener) {
        this.onSelectImgFinishListener = onSelectImgFinishListener;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public void refresh() {
        loadData();
    }

    @Override
    public View getView() {
        return panelView;
    }

    @Override
    public void init() {
        handler = new Handler(this);
        initUI();
        addILFMsgListener(this);
    }

    private void initUI() {
        panelView = new LinearLayout(context);
        panelView.setOrientation(LinearLayout.VERTICAL);

        //================菜单=====================
        LinearLayout menuLayout = new LinearLayout(context);
        menuLayout.setOrientation(LinearLayout.HORIZONTAL);
        menuLayout.setGravity(Gravity.CENTER_VERTICAL);
        menuLayout.setBackgroundColor(Color.parseColor("#098edd"));
        panelView.addView(menuLayout, LayoutParams.MATCH_PARENT, Util.dip2px(context, 50));

        backIV = new ImageView(context);
        backIV.setBackgroundResource(R.mipmap.back);
        LayoutParams personLP = new LayoutParams(Util.dip2px(context, 18), Util.dip2px(context, 14));
        personLP.leftMargin = Util.dip2px(context, 15);
        personLP.rightMargin = Util.dip2px(context, 6);
        menuLayout.addView(backIV, personLP);
        backIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OnDestroy();
                closeForm();
            }
        });

        //标题
        TextView titleView = new TextView(context);
        titleView.setTextColor(Color.WHITE);
        titleView.setTextSize(18f);
        titleView.setGravity(Gravity.CENTER);
        titleView.setText("照片");
        LayoutParams titleLP = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        titleLP.weight = 1;
        menuLayout.addView(titleView, titleLP);

        photosBtn = new Button(context);
        photosBtn.setBackgroundDrawable(null);
        photosBtn.setText("相册");
        photosBtn.setTextColor(Color.WHITE);
        photosBtn.setPadding(Util.dip2px(context, 5), 0, Util.dip2px(context, 5), 0);
        LayoutParams photoLP = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        photoLP.rightMargin = Util.dip2px(context, 6);
        menuLayout.addView(photosBtn, photoLP);
        photosBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPop();
            }
        });

        //=================================
        RelativeLayout relativeLayout = new RelativeLayout(context);
        panelView.addView(relativeLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        //gridView
        gridView = new GridView(context);
        gridView.setCacheColorHint(Color.parseColor("#00000000"));
        gridView.setClipChildren(true);
        gridView.setGravity(Gravity.CENTER);
        gridView.setHorizontalSpacing(Util.dip2px(context, 3));
        gridView.setNumColumns(3);
        //stretchMode属性值的作用是设置GridView中的条目以什么缩放模式去填充剩余空间。
        gridView.setStretchMode(STRETCH_COLUMN_WIDTH);
        int padding = Util.dip2px(context, 3);
        gridView.setPadding(padding, padding, padding, padding);
        gridView.setVerticalSpacing(Util.dip2px(context, 3));
        relativeLayout.addView(gridView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

        photoAdapter = new PhotoAdapter(context, mode, maxSelectPhotoNum);
        photoAdapter.setHandler(handler);
        photoAdapter.setImages(mImgs);
        gridView.setAdapter(photoAdapter);
    }

    private void loadData() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(context, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    ContentResolver mContentResolver = context.getContentResolver();

                    // 只查询jpeg和png的图片
                    Cursor mCursor = mContentResolver.query(mImageUri, null,
                            MediaStore.Images.Media.MIME_TYPE + "=? or "
                                    + MediaStore.Images.Media.MIME_TYPE + "=?",
                            new String[]{"image/jpeg", "image/png"},
                            MediaStore.Images.Media.DATE_MODIFIED);

                    Log.e("TAG", mCursor.getCount() + "");
                    while (mCursor.moveToNext()) {
                        // 获取图片的路径
                        String path = mCursor.getString(mCursor
                                .getColumnIndex(MediaStore.Images.Media.DATA));

                        Log.e("TAG", path);
                        // 获取该图片的父路径名
                        File parentFile = new File(path).getParentFile();
                        if (parentFile == null)
                            continue;
                        String dirPath = parentFile.getAbsolutePath();
                        ImageFloder imageFloder = null;
                        // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                        if (mDirPaths.contains(dirPath)) {
                            continue;
                        } else {
                            mDirPaths.add(dirPath);
                            // 初始化imageFloder
                            imageFloder = new ImageFloder();
                            imageFloder.setDir(dirPath);
                            imageFloder.setFirstImagePath(path);
                        }

                        int picSize = parentFile.list(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String filename) {
                                if (filename.endsWith(".jpg")
                                        || filename.endsWith(".png")
                                        || filename.endsWith(".jpeg"))
                                    return true;
                                return false;
                            }
                        }).length;

                        imageFloder.setCount(picSize);
                        mImageFloders.add(imageFloder);

                        if (picSize > mPicsSize) {
                            mPicsSize = picSize;
                            mImgDir = parentFile;
                        }
                    }
                    mCursor.close();

                    // 扫描完成，辅助的HashSet也就可以释放内存了
                    mDirPaths = null;

                    if (null != handler) {
                        // 通知Handler扫描图片完成
                        handler.sendEmptyMessage(100);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {//点击返回按键
            OnDestroy();
            closeForm();
        }
        return null;
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case 100: {
                // 为View绑定数据
                data2View();
                break;
            }
            case 200: {
                if (mode == 1) {
                    if (null != onSelectImgFinishListener) {
                        onSelectImgFinishListener.onSelectFinish(this, photoAdapter.getmSelectedImage());
                    }
                    OnDestroy();
                    closeForm();
                }
                break;
            }
        }
        return false;
    }

    /**
     * 为View绑定数据
     */
    private void data2View() {
        if (mImgDir == null) {
            Toast.makeText(context, "没有扫描到图片", Toast.LENGTH_SHORT).show();
            return;
        }

        mImgs = Arrays.asList(mImgDir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg")) {
                    return true;
                }
                return false;
            }
        }));
        /**
         * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
         */
        if (null != photoAdapter) {
            if (null != mImgDir) {
                photoAdapter.setmDirPath(mImgDir.getAbsolutePath());
            }
            photoAdapter.setImages(mImgs);
            photoAdapter.notifyDataSetChanged();
        }
    }


    /**
     * 显示相册列表
     */
    private void showPop() {
        if (popupWindow == null) {
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
            linearLayout.setGravity(Gravity.BOTTOM);
            linearLayout.setClickable(true);

            PhotoListAapter photoListAapter = new PhotoListAapter(context);
            photoListAapter.setmImageFloders(mImageFloders);

            ListView listView = new ListView(context);
            listView.setBackgroundColor(Color.parseColor("#ffffff"));
            listView.setDivider(new ColorDrawable(Color.parseColor("#dadada")));
            listView.setDividerHeight(1);
            linearLayout.addView(listView, LayoutParams.MATCH_PARENT, (int) (Util.getScreenHeight(context) * 0.55));
            listView.setAdapter(photoListAapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (null != mImageFloders) {
                        ImageFloder imageFloder = mImageFloders.get(i);
                        if (null != imageFloder) {
                            mImgDir = new File(imageFloder.getDir());
                            mImgs = Arrays.asList(mImgDir.list(new FilenameFilter() {
                                @Override
                                public boolean accept(File dir, String filename) {
                                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                            || filename.endsWith(".jpeg"))
                                        return true;
                                    return false;
                                }
                            }));

                            if (null != photoAdapter) {
                                if (null != mImgDir) {
                                    photoAdapter.setmDirPath(mImgDir.getAbsolutePath());
                                }
                                photoAdapter.setImages(mImgs);
                                photoAdapter.notifyDataSetChanged();
                            }
                            popupWindow.dismiss();
                        }
                    }
                }
            });

            popupWindow = new PopupWindow(linearLayout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            popupWindow.setAnimationStyle(R.style.photoppw_anim_style);
            popupWindow.setTouchable(true);
            popupWindow.setFocusable(true);
            //需要设置为ture，表示可以聚焦
            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            popupWindow.setOutsideTouchable(true);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    backgroundAlpha(1f);
                }
            });
        }

        popupWindow.showAtLocation(panelView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        backgroundAlpha(0.5f);
    }

    //修改屏幕透明度
    public void backgroundAlpha(float bgAlpha) {
        Window window = ((Activity) context).getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        if (bgAlpha == 1) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        window.setAttributes(lp);
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        if (mImgs != null) {
            mImgs = null;
        }
        if (null != mImageFloders) {
            mImageFloders.clear();
            mImageFloders = null;
        }
        if (null != popupWindow) {
            popupWindow.dismiss();
            popupWindow = null;
        }
        if (null != gridView) {
            gridView.setAdapter(null);
            gridView = null;
        }
        removeILFMsgListener(this);

        handler = null;
        panelView = null;
    }

    public interface OnSelectImgFinishListener {
        void onSelectFinish(PhotoSelectView photoView, List<String> list);
    }
}
